<template>
	<gzPageWrapper
		ref="gzPageWrapperRef"
		:styles="{ background: '#F7F8FB url(https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/f7e195d9-966c-4ac0-a53d-216a7c4457bc.png) no-repeat 0 0 / 100% 670rpx' }"
		:nav="{ title: '福分商城', color: '#fff', leftIcon: 'left' }"
		:up="{ use: true, auto: false, page: { num: 1, size: 10 }, textNoMore: '--暂无更多--', empty: { use: false } }"
		:down="{ auto: false, auto: false }"
		@upCallback="upCallback"
	>
		<template #default>
			<view class="inner">
				<view class="top-content">
					<text>我的福分</text>
					<text>{{ vdata.scoreTotal }}</text>
				</view>
				<view class="content-wrap">
					<view class="list">
						<view class="item" v-for="item in vdata.scoreMallList">
							<view class="remain">剩余：{{ item.syNum }}</view>
							<view class="left">
								<view class="amount" :style="{ backgroundImage: `url(https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/3dd1efb6-9cc4-4694-b461-e2d25ee7af9a.png)` }">
									<text>￥</text>
									<text>{{ item.price ? item.price / 100 : 0 }}</text>
									<view>满{{item.payAmount ? item.payAmount / 100 : '--'}}元可用</view>
								</view>
								<view v-if="item.awardType == 0" class="type coupon">卡券</view>
								<view v-if="item.awardType == 1" class="type coupon">实物</view>
								<view v-if="item.awardType == 2" class="type coupon">虚拟券</view>
							</view>
							<view class="right">
								<view class="info">
									<view class="title">{{ item.name }}</view>
									<!-- <view class="desc">奖品价值：{{ item.price ? item.price / 100 : 0 }}</view> -->
									<view class="over-time">已兑换：{{ item.getNum }}</view>
								</view>
								<view class="exchange">
									<view class="btn" @tap="scoreExchange(item)">立即兑换</view>
									<view class="need">{{ item.scoreNeed }}福分</view>
								</view>
							</view>
						</view>
					</view>
					<gzListNull :list="vdata.scoreMallList"></gzListNull>
				</view>
			</view>
		</template>
	</gzPageWrapper>
</template>

<script setup>
	import dayjs from 'dayjs'
	import storageManage from '@/util/storageManage.js'
	import { reactive, ref, getCurrentInstance, nextTick } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { $scoreMallList, $scoreCoupon, $scoreExchange, $checkUserPayAuth } from '@/http/apiManager.js';
	import appConfig from '@/config/appConfig';
	
	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties
	
	const gzPageWrapperRef = ref()
	
	const vdata = reactive({
		scoreMallList: [],	// 福分商城列表
		scoreTotal: 0,	// 总福分数
	})
	const userId = storageManage.userId()
	const fansId = storageManage.fansId()
	
	const navData = reactive({
		statusBarHeight: getApp().globalData.statusBarHeight,
		navbarHeight: getApp().globalData.navbarHeight
	})
	
	onLoad(async ({ item })=>{
		// 刷新福分数量
		await getScoreCoupon()
		nextTick(() => {
			gzPageWrapperRef.value.getMescroll().resetUpScroll()
		})
		// 自动兑换
		if(item){
			item = JSON.parse(decodeURIComponent(item))
			uni.showLoading({ title: '兑换中...', mask: true })
			exchangeHandler(item)
		}
	})
	// 获取福分数量
	async function getScoreCoupon(){
		await $scoreCoupon().then(({ bizData } )=> {
			// 福分数量
			vdata.scoreTotal = bizData.score
		})
	}
	// 商城兑换
	function scoreExchange(item){
		getApp().preventActive(async () => {
			if(item.syNum == 0){
				$infoBox.toast('商品已兑完！')
				return
			}
			uni.showModal({
				title: '兑换提示',
				content: `请确定是否消耗${item.scoreNeed}福分兑换该奖品`,
				async success({ cancel }) {
					if(cancel) return
					// 校验余量
					if(item.scoreNeed - 0 > vdata.scoreTotal - 0){
						$infoBox.toast('剩余福分不足！')
						return
					}
					uni.showLoading({ title: '兑换中...', mask: true })
					// 校验出资方
					if(item.ifCode){	// 当前卡券为三方出资
						// 判断本地是否缓存支付授权
						if(!storageManage.openId(`${item.ifCode}-openId`)){	// 本地不存在支付授权 请求授权参数进行授权
							const { bizData:payAuthBizData } = await $checkUserPayAuth({ scoreExchangeId: item.scoreExchangeId })
							const { flag, url, ifCode } = payAuthBizData
							if(url && ifCode){	// 说明用户未授权
								uni.hideLoading()
								// 跳转授权页面
								appConfig.url = url
								getApp().globalData.temp_path = `/pageScore/scoreMall/index?item=${encodeURIComponent(JSON.stringify(item))}`
								getApp().globalData.temp_ifcode = ifCode
								uni.redirectTo({
									url: '/pages/openid/openid'
								})
								return
							}
						}
					}
					// 发起兑换
					exchangeHandler(item)
				}
			})
		})
	}
	
	// 发起兑换处理 item 兑换对象 信息
	async function exchangeHandler(item){
		// 已授权且用户福分余量充足 允许兑换奖品
		const { code, bizData } = await $scoreExchange({ infoType: item.awardType - 0, scoreExchangeId: item.scoreExchangeId, name: item.name })
		if(code === 40006){	// 5分钟内进行过一次兑换
			uni.hideLoading()
			uni.showModal({
				title: '提示',
				content: bizData || '您已兑换成功，是否需要再次兑换？',
				async success({ cancel }) {
					if (cancel) return
					// 用户确认兑换
					uni.showLoading({ title: '兑换中...', mask: true })
					await $scoreExchange({ infoType: item.awardType - 0, scoreExchangeId: item.scoreExchangeId, name: item.name, state: 1 })
					// 刷新福分数量
					getScoreCoupon()
					// 刷新商城列表
					gzPageWrapperRef.value.getMescroll().resetUpScroll()
					$infoBox.toast('兑换成功！')
				}
			})
		}else{
			// 刷新福分数量
			getScoreCoupon()
			// 刷新商城列表
			gzPageWrapperRef.value.getMescroll().resetUpScroll()
			$infoBox.toast('兑换成功！')
		}
	}
	
	/**
	 * upCallback下拉刷新以及上拉加载 刷新列表
	 */
	
	const upCallback = (mescroll) => {
		const { size, num } = mescroll
		$scoreMallList({ agentNo: storageManage.agentInfo().agentNo, pageSize: size, pageNumber: num }).then(({ bizData }) => {
			mescroll.endSuccess(bizData.records.length,bizData.hasNext)
			if(num === 1) vdata.scoreMallList = [];
			vdata.scoreMallList = vdata.scoreMallList.concat(bizData.records)
		}).catch(() => {
			mescroll.endErr()
		})
	}
</script>

<style lang="less">
	.inner{
		overflow: hidden;
		padding: 0 36rpx;
		.top-content{
			margin-top: 55rpx;
			display: flex;
			flex-direction: column;
			color: #fff;
			text{
				&:nth-child(1){
					font-size: 28rpx;
				}
				&:nth-child(2){
					font-size: 28rpx;
					font-weight: bold;
					font-size: 76rpx;
					margin-top: 32rpx;
				}
			}
		}
		.content-wrap{
			.list{
				// padding: 30rpx;
				margin-top: 40rpx;
				width: 100%;
				box-sizing: border-box;
				display: flex;
				flex-direction: column;
				gap: 24rpx;
				
				.item{
					display: flex;
					position: relative;
					.remain{
						position: absolute;
						right: 0;
						top: 0;
						font-size: 24rpx;
						color: #24C789;
						background: #E9F9F3;
						border-radius: 0rpx 16rpx 0rpx 16rpx;
						padding: 10rpx 16rpx;
					}
					.left{
						width: 220rpx;
						height: 220rpx;
						// flex: 2;
						flex-shrink: 0;
						position: relative;
						
						.amount{
							// padding: 46rpx 0;
							width: 220rpx;
							height: 170rpx;
							background-size: 100% 100%;
							background-repeat: no-repeat;
							background-position: 0 0;
							flex-shrink: 0;
							color: #fff;
							position: relative;
							overflow: hidden;
							display: flex;
							align-items: center;
							justify-content: center;
							border-radius: 20rpx 0 0 0;
							overflow: hidden;
							position: relative;
							
							text{
								position: relative;
								z-index: 99;
								&:nth-of-type(1){
									font-weight: bold;
									font-size: 32rpx;
								}
								&:nth-of-type(2){
									font-weight: bold;
									font-size: 60rpx;
								}
							}
							view{
								font-weight: normal;
								font-size: 24rpx;
								position: absolute;
								bottom: 10rpx;
							}
						}
						.type{
							height: 50rpx;
							background: #FADB9A;
							color: #B17622;
							// padding: 14rpx 0;
							text-align: center;
							line-height: 50rpx;
							border-radius: 0 0 0 20rpx;
							font-size: 24rpx;
							position: relative;
							background: #FADB9A;
							
						}
						.coupon{
							background: radial-gradient(circle at right bottom, transparent 10rpx,#FADB9A 0, #FADB9A 100%);
							&::after {
								content: '';
								// height: 80px;
								height: 100%;
								border-right: 10rpx dotted #fff;
								position: absolute;
								right: -6rpx;
								top: -18rpx;
								bottom: 0;
								margin: auto;
							}
						}
					}
					.right{
						padding: 0 24rpx;
						box-sizing: border-box;
						width: calc(100% - 220rpx);
						display: flex;
						align-items: center;
						justify-content: space-between;
						background-color: #fff;
						border-radius: 0 20rpx 20rpx 0;
						
						.info{
							width: calc(100% - 136rpx);
							padding-right: 24rpx;
							box-sizing: border-box;
							.title{
								font-weight: bold;
								font-size: 32rpx;
								color: #333333;
								overflow: hidden;
								text-overflow: ellipsis;
								white-space: nowrap;
								margin-bottom: 20rpx;
							}
							// .desc{
							// 	font-weight: 400;
							// 	font-size: 26rpx;
							// 	color: #FF8833;
							// 	margin: 20rpx 0 16rpx 0;
							// }
							.over-time{
								font-weight: 400;
								font-size: 26rpx;
								color: #666666;
							}
						}
						.exchange{
							display: flex;
							align-items: center;
							justify-content: center;
							flex-direction: column;
							.btn{
								width: 136rpx;
								height: 56rpx;
								background: #FF8833;
								box-shadow: 0rpx 4rpx 12rpx 0rpx rgba(255,136,51,0.4);
								border-radius: 35rpx;
								color: #fff;
								font-size: 24rpx;
								line-height: 56rpx;
								text-align: center;
							}
							.need{
								font-size: 24rpx;
								color: #FF8833;
								margin-top: 12rpx;
							}
						}
					}
				}
			}
		}
	}
</style>